// pages/Tabbar/Classification/Classification.js
//获取应用实例
const app = getApp();
import { getGoodsClassification , queryGoodsCommonConfig , queryGoodsListTab , queryGoodsDeliveryTime , queryGoodsSearchHistory } from '../../../api/goods';
import { throttle } from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBgColor: 'linear-gradient(to right,#CC6CA8,#E3545F,#3F0D7D)',
    tabNavTop: app.globalData.CustomBar,
    shareTitle: app.globalData.global.shareTitle,
    soltMarginRight: app.globalData.soltMarginRight,
    areaId: '0',
    cateList: [],
    cateId: '',
    page: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    refresher: false,
    total: 0,
    dataList: [],
    scrollHeight: 0, // 滚动模块高度
    activeKey: 0,
    colorId: '', // 颜色ID
    isCollect: '', // 是否收藏
    sellingPriceSort: '', // 售价排序(ASC:正序,DESC:倒叙)
    salesVolumeSort: 'DESC', // 销量排序(ASC:正序,DESC:倒叙)
    isShowColorSel: false, // 颜色选择框
    colors: [], // 颜色分类
    storehouseId: '', // 仓库ID
    name: '', // 商品名称
    province: '上海市',
    city: '上海市',
    country: '浦东新区',
    deliveryStartTime: '',
    deliveryEndTime: '',
    sortType: 'volume',
    tabList: [], // 主分类
    custombar: app.globalData.CustomBar,
    parentId: '',
    showSeachHistory: false,
    searchHistoryList: [], // 历史搜索记录
    mainCateId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    _this._getGoodsColorInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    var storehouseId = wx.getStorageSync('storehouseId');
    var areaId = wx.getStorageSync('areaId');
    console.log('走了这里111',storehouseId)
    if(storehouseId != _this.data.storehouseId){
      this.setData({
        storehouseId: storehouseId,
        page: 0,
        // areaId: areaId
      })
      console.log('走了这里')
      _this._getGoodsClassification(0);
      wx.createSelectorQuery().select('.cateCont').boundingClientRect(res => {
        console.log(res,'分类块')
        _this.setData({
          scrollHeight: res.height,
        })
      }).exec();
    }
    var stCountry = wx.getStorageSync('country');
    if(_this.data.country != stCountry && stCountry){
      _this.setData({
        province: wx.getStorageSync('province'),
        city: wx.getStorageSync('city'),
        country: stCountry,
      })
    }
    _this._queryGoodsDeliveryTime();
    _this.setData({
      searchHistoryList: wx.getStorageSync('searchHistoryList') ? wx.getStorageSync('searchHistoryList') : [],
      showSeachHistory: false,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function(){
    let _this = this;
    _this.setData({
      page: 0,
      name: '',
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    _this._getGoodsColorInfo();
    // _this._getGoodsClassification(0);
    _this._getGoods();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          _this.setData({
            refresher: false
          })
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1500)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取商品颜色分类信息
  _getGoodsColorInfo(){
    let _this = this;
    queryGoodsCommonConfig({size: 99,type: '2'})
    .then(res => {
      if(res.success){
        _this.setData({
          colors: res.data.content,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品分类信息
  _getGoodsClassification(parentId){
    let _this = this;
    getGoodsClassification({size: 99,parentId: parentId,level: parentId == 0 ? 1 : 2})
    .then(res => {
      console.log('获取分类信息')
      if(res.success){
        // _this.setData({
        //   cateList: [{id: '', cateName: '全部'},...res.data.content],
        // })
        // if(res.data.content.length > 0){
        //   _this._getGoods();
        // }
        if(parentId == 0){
          _this.setData({
            tabList: res.data.content,
          })
          for (let index = 0; index < res.data.content.length; index++) {
            const item = res.data.content[index];
            if(item.cateName == '切花类'){
              _this.setData({
                parentId: item.id,
              })
              _this._getGoodsClassification(item.id);
            }
          }
        }else{
          var idsArr = [];
          for (let index = 0; index < res.data.content.length; index++) {
            const item = res.data.content[index];
            idsArr.push(item.id);
          }
          _this.setData({
            cateList: [{id: idsArr.join(','), cateName: '全部'},...res.data.content],
            // cateList: [...res.data.content],
          })
          if(res.data.content.length > 0){
            _this.setData({
              // cateId: res.data.content[0].id,
              cateId: idsArr.join(','),
              mainCateId: idsArr.join(','),
              page: 0,
            })
            _this._getGoods();
          }else{
            _this.setData({
              dataList: [],
            })
          }
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 根据分类获取商品列表信息
  _getGoods(){
    let _this = this;
    if(_this.data.name != ''){
      var hasHistory = _this.data.searchHistoryList.indexOf(_this.data.name);
      if(hasHistory == -1){
        var lists = [];
        lists = _this.data.searchHistoryList;
        console.log(lists,'lists')
        lists.unshift(_this.data.name);
        if(lists.length > 60){
          lists.splice(lists.length - 1,1)
        }
        wx.setStorageSync('searchHistoryList', lists);
        _this.setData({
          searchHistoryList: lists,
        })
      }
    }
    queryGoodsListTab({cateId: _this.data.cateId,storehouseId: _this.data.storehouseId,page: _this.data.page,isCollect: _this.data.isCollect,colorId: _this.data.colorId,sellingPriceSort: _this.data.sortType == 'price' ? _this.data.sellingPriceSort : '',salesVolumeSort: _this.data.sortType == 'volume' ? _this.data.salesVolumeSort : '',areaId: _this.data.areaId,goodsName: _this.data.name})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        if(_this.data.page == 0){
          list = res.data.content;
        }else{
          list = list.concat(res.data.content);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 分类切换
  cateChange(e){
    console.log(e,'index')
    console.log(this.data.activeKey,'activekey')
    this.setData({
      page: 0,
      cateId: this.data.cateList[e.detail].id,
      activeKey: e.detail,
      name: '',
    })
    if(this.data.cateList[e.detail].id != ''){
      this._getGoods();
    }
  },
  // 加载更多数据
  onLoadMore: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._getGoods()
    }
  },500),
  // 选择价格或销量排序
  selSort(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(item == 'price'){
      var sellingPriceSort = this.data.sellingPriceSort == 'DESC' ? 'ASC' : 'DESC'
      this.setData({
        sellingPriceSort: sellingPriceSort,
        page: 0,
        isShowColorSel: false,
        sortType: 'price',
      })
    }else{
      var salesVolumeSort = this.data.salesVolumeSort == 'ASC' ? 'DESC' : 'ASC'
      this.setData({
        salesVolumeSort: salesVolumeSort,
        page: 0,
        isShowColorSel: false,
        sortType: 'volume',
      })
    }
    this._getGoods()
  },
  // 选择颜色分类
  showSleColor(){
    let _this = this;
    this.setData({
      isShowColorSel: _this.data.isShowColorSel ? false : true,
    })
  },
  selColor(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      colorId: _this.data.colorId != '' ? '' : item.id,
      page: 0,
      isShowColorSel: false
    })
    this._getGoods();
  },
  // 关闭颜色选择器
  closeColorSeltor(){
    this.setData({
      isShowColorSel: false
    })
  },
  // 是否常用
  isCollectChange(){
    // var isCollect = this.data.isCollect == 1 ? '' : '1';
    this.setData({
      isCollect: this.data.isCollect == 1 ? '' : '1',
      page: 0,
      isShowColorSel: false
    })
    this._getGoods();
  },
  // 重置筛选条件
  reset(){
    this.setData({
      colorId: '',
      isCollect: '',
      order: '',
      sort: '',
      name: '',
      page: 0,
      isShowColorSel: false,
      sellingPriceSort: '',
      salesVolumeSort: '',
      sortType: '',
    })
    if(this.data.cateId != ''){
      this._getGoods();
    }
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(this.data.parentId,'parentId')
    // console.log(this.data.tabList,'tablist')
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        var cateParent = this.data.tabList.find(item => item.id == this.data.parentId);
        var cateParentName = cateParent.cateName;
        var cate = this.data.cateList.find(cate => cate.id == item.cateId);
        var cateName = cate.cateName;
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}&cateParentName=${JSON.stringify(cateParentName)}&cateName=${JSON.stringify(cateName)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
      
    }
  },
  // 输入框发生变化
  onSearchChange(e) {
    this.setData({
      name: e.detail,
    });
  },
  // 输入框搜索
  onSearch(){
    let _this = this;
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      showSeachHistory: false,
      cateId: _this.data.mainCateId,
      activeKey: 0,
    })
    this._getGoods();
  },
  noEve(){},
  // 获取送达时间
  _queryGoodsDeliveryTime(){
    let _this = this;
    queryGoodsDeliveryTime({province: _this.data.province,city: _this.data.city,area: _this.data.country})
    .then(res => {
      if(res.success){
        _this.setData({
          deliveryStartTime: res.data.deliveryStartTime,
          deliveryEndTime: res.data.deliveryEndTime,
        })
      }else{
        // wx.showToast({
        //   title: res.errMessage,
        //   icon: 'none',
        // })
      }
    })
  },
  // 主分类切换
  selParentCate(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item);
    this.setData({
      parentId: item.id,
      cateId: '',
      name: '',
    })
    this._getGoodsClassification(item.id);
  },
  // 搜索框获取焦点
  onSearchFocus(){
    this.setData({
      showSeachHistory: true,
    })
  },
  closeSearchHistoryWrap(){
    console.log('关闭')
    this.setData({
      showSeachHistory: false,
    })
  },
  // 获取历史搜索记录
  getSearchHistory(){
    let _this = this;
    queryGoodsSearchHistory()
    .then(res => {
      if(res.success){
        _this.setData({
          searchHistoryList : res.data,
        })
      }else{

      }
    })
  },
  setSearch(e){
    console.log(e,'e')
    let _this = this;
    console.log(_this.data.mainCateId,'mainCateId')
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      name: item,
      page: 0,
      showSeachHistory: false,
      cateId: _this.data.mainCateId,
      activeKey: 0,
    });
    console.log(this.data.name);
    this._getGoods();
  }
})